//
//  XMConversationListViewController.m
//  XunMi
//
//  Created by MacBook on 2024/2/18.
//  Copyright © 2024 TieZhu. All rights reserved.
//

#import "XMConversationListViewController.h"
#import "XMMsgToolsView.h"
#import "XMMsgNoRealView.h"
#import "XMIntimacyViewController.h"
#import "XMFollowViewController.h"
#import "XMRealViewController.h"
#import "XMGuardViewController.h"
#import "XMZanViewController.h"
#import "XMConversationViewController.h"
#import "XMNoDisturbTipView.h"
#import "XMDisturbTypeView.h"
#import "XMConversationListHeaderView.h"
#import "XMUserDetailViewController.h"
#import "RCKitUtility.h"
#import "XMTabBarViewController.h"

@interface XMConversationListViewController ()
@property (nonatomic, strong) UIButton *searchBtn;
@property (nonatomic, strong) XMMsgToolsView *toolsView;
@property (nonatomic, strong) XMMsgNoRealView *norealView;
@property (nonatomic, strong) XMNoDisturbTipView *disturbTipView;
@property (nonatomic, strong) XMDisturbTypeView *disturbTypeView;
@property (nonatomic, strong) XMConversationListHeaderView *conversationListHeaderView;
@property (nonatomic, strong) UIView *lineView;
@property (nonatomic, assign) BOOL norealClose;
@end

@implementation XMConversationListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupSubviews];
    [self setupConversationList];
    [self subViewsBlock];
    [self muteState];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self notifyUpdateUnreadMessageCount];
    [self updateNorealLayout];
}

#pragma mark - data
- (void)muteState {
    NSMutableDictionary *dic = @{
        @"module": @"5"
    }.mutableCopy;
    [YHNetworkManager.sharedInstance postWithUrl:@"api/user/obtain" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
        if (tip.success) {
            kUserModel.is_mute = [@([result toInt:@"state"]) boolValue];
            self.disturbTipView.hidden = NO;
            [self.disturbTipView reload];
        }
    }];
}

#pragma mark - Block
- (void)subViewsBlock {
    XMWeakSelf(self);
    self.toolsView.toolsBlock = ^(XMMsgToolsModel * _Nonnull model) {
        XMStrongSelf(self);
        switch (model.type) {
            case XMMsgToolsNotice:
            {
                XMIntimacyViewController *vc = [[XMIntimacyViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            } break;
                
            case XMMsgToolsGuard:
            {
                XMGuardViewController *vc = [[XMGuardViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            } break;
                
            case XMMsgToolsFollow:
            {
                XMFollowViewController *vc = [[XMFollowViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            } break;
                
            case XMMsgToolsLike:
            {
                XMZanViewController *vc = [[XMZanViewController alloc] init];
                [self.navigationController pushViewController:vc animated:YES];
            } break;
            default:
                break;
        }
    };
    
    self.norealView.toRealBlock = ^{
        XMStrongSelf(self);
        XMRealViewController *vc = [[XMRealViewController alloc] initWithNibName:kStringFromClass(XMRealViewController) bundle:nil];
        [self.navigationController pushViewController:vc animated:YES];
    };
    
    self.norealView.closeBlock = ^{
        XMStrongSelf(self);
        self.norealClose = YES;
        [self updateNorealLayout];
    };
    
    self.disturbTipView.changeBlock = ^{
        XMStrongSelf(self);
        [self showDisturbTypeView];
    };
    
    self.conversationListHeaderView.checkBlock = ^(RCConversationModel * _Nonnull model) {
        XMStrongSelf(self);
        [self toConversationViewController:model];
    };
    
    self.conversationListHeaderView.systemBlock = ^(RCConversationModel * _Nonnull model) {
        XMStrongSelf(self);
        [self toConversationViewController:model];
    };
    self.disturbTypeView.changeBlock = ^(BOOL disturb) {
        XMStrongSelf(self);
        [MBProgressHUD showHUDActivityMsg:nil  toView:kWindow];
        NSMutableDictionary *dic = @{
            @"is_mute": @(disturb ? 1 : 0)
        }.mutableCopy;
        [YHNetworkManager.sharedInstance postWithUrl:@"api/user/update" parameters:dic completeBlock:^(XMResponseTip * _Nonnull tip, id  _Nullable result) {
            if (tip.success) {
                [MBProgressHUD hideHUD];
                XMWeakSelf(self);
                [GKCover hideCoverWithHideBlock:^{
                    XMStrongSelf(self);
                    kUserModel.is_mute = disturb;
                    [self.disturbTipView reload];
                }];
            }
        }];
    };
}

#pragma mark - setupSubviews

- (void)setupSubviews {
    [self.navLeftBtn setTitle:@"消息" forState:UIControlStateNormal];
    [self.navLeftBtn setImage:nil forState:UIControlStateNormal];
    self.navLeftBtn.titleLabel.font = kUIFontBold(19);
    [self.navLeftBtn setTitleColor:k1F1F1F forState:UIControlStateNormal];
    [self.navLeftBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(70, 44));
    }];
    
    self.disturbTipView = [XMNoDisturbTipView viewFromXib];
    self.disturbTipView.hidden = YES;
    [_disturbTipView radiusWithRadius:13 corner:(UIRectCornerAllCorners)];
    [self.navView addSubview:_disturbTipView];
    [_disturbTipView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.size.mas_equalTo(CGSizeMake(68, 26));
        make.left.equalTo(self.navLeftBtn.mas_right).offset(0);
        make.centerY.equalTo(self.navLeftBtn);
    }];
    
    self.navRightBtn.adjustsImageWhenHighlighted = NO;
    [self.navRightBtn setImage:kGetImage(@"notice_clear") forState:UIControlStateNormal];
    [self.navRightBtn setImage:kGetImage(@"notice_clear_s") forState:UIControlStateSelected];
    [self.navRightBtn addTarget:self action:@selector(clear) forControlEvents:UIControlEventTouchUpInside];
    
    //    [self.navView addSubview:self.searchBtn];
    //    [self.searchBtn mas_makeConstraints:^(MASConstraintMaker *make) {
    //        make.centerY.equalTo(self.navRightBtn);
    //        make.right.equalTo(self.navRightBtn.mas_left).offset(-14);
    //        make.size.mas_equalTo(CGSizeMake(86, 36));
    //    }];
    
    self.toolsView = [XMMsgToolsView viewFromXib];
    [self.view addSubview:_toolsView];
    
    [self.toolsView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.height.mas_equalTo(72);
        make.top.mas_equalTo(self.navView.mas_bottom).offset(20);
    }];
    
    self.lineView = [[UIView alloc] init];
    self.lineView.backgroundColor = kHEXA(@"#8C8F9D", 0.08);
    [self.view addSubview:self.lineView];
    [self.view addSubview:self.norealView];
    [self updateNorealLayout];
}

- (void)updateNorealLayout {
    self.norealView.hidden = kUserModel.idcard_verify || self.norealClose;
    if (!kUserModel.idcard_verify && !self.norealClose) {
        [self.norealView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.toolsView.mas_bottom).offset(14);
            make.left.equalTo(self.view).offset(20);
            make.right.equalTo(self.view).offset(-20);
            make.height.mas_equalTo(48);
        }];
        
        [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.norealView.mas_bottom).offset(14);
            make.left.equalTo(self.view).offset(0);
            make.right.equalTo(self.view).offset(0);
            make.height.mas_equalTo(10);
        }];
    } else {
        [self.lineView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.toolsView.mas_bottom).offset(14);
            make.left.equalTo(self.view).offset(0);
            make.right.equalTo(self.view).offset(0);
            make.height.mas_equalTo(10);
        }];
    }
    
    [self.conversationListTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.lineView.mas_bottom).offset(0);
        make.bottom.equalTo(self.view).offset(-kTabBarHeight);
    }];
    
    [self.emptyConversationView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self.conversationListTableView);
    }];
}

#pragma mark - setupConversationList
- (void)setupConversationList {
    self.displayConversationTypeArray = @[@(ConversationType_PRIVATE), @(ConversationType_SYSTEM)];
    self.conversationListTableView.backgroundColor = UIColor.clearColor;
    self.cellBackgroundColor = UIColor.clearColor;
    self.topCellBackgroundColor = [UIColor xm_colorWithHexString:@"#D3D3D3" alpha:0.3];
    self.conversationListTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    self.conversationListTableView.separatorColor = UIColor.clearColor;
    [self.conversationListTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.top.equalTo(self.lineView.mas_bottom).offset(0);
    }];
    XMConversationListHeaderView *header = [[XMConversationListHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 140)];
    self.conversationListTableView.tableHeaderView = header;
    self.conversationListHeaderView = header;
}

#pragma mark - Actions
- (void)clear {
    [XMAlertHelper alertTitle:@"是否清空全部未读消息?"
                      message:nil
                  cancelTitle:@"取消"
                    sureTitle:@"确定"
                 cancelAction:nil
                   sureAction:^{
        [self clearAll];
    }];
}

- (void)clearAll {
    [[RCCoreClient sharedCoreClient] getConversationList:@[
        @(ConversationType_PRIVATE),
        @(ConversationType_SYSTEM)
    ] completion:^(NSArray<RCConversation *> *_Nullable conversationList) {
        NSMutableArray *syncConversations = [[NSMutableArray alloc] init];
        for (int i = 0; i < conversationList.count; i++) {
            RCConversation *conversation = conversationList[i];
            if (conversation.unreadMessageCount > 0) {
                [[RCCoreClient sharedCoreClient] clearMessagesUnreadStatus:conversation.conversationType
                                                                  targetId:conversation.targetId
                                                                completion:^(BOOL ret){}];
                [syncConversations addObject:conversation];
            }
        }
        [self refreshConversationTableViewIfNeeded];
        for (RCConversation *conversation in syncConversations) {
            [NSThread sleepForTimeInterval:0.2];
            [RCKitUtility syncConversationReadStatusIfEnabled:(RCConversationModel *)conversation];
        }
    }];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    XMTabBarViewController *tabBar = (XMTabBarViewController *)[UIViewController currentViewController].tabBarController;
    [tabBar.tabBarView setBadgeNum:0];
    self.navRightBtn.selected = NO;
}

#pragma mark - super Method
// 高度
-(CGFloat)rcConversationListTableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70;
}

- (void)onSelectedTableRow:(RCConversationModelType)conversationModelType conversationModel:(RCConversationModel *)model atIndexPath:(NSIndexPath *)indexPath {
    [self toConversationViewController:model];
}

- (void)toConversationViewController:(RCConversationModel *)model {
    XMConversationViewController *conversationVC = [[XMConversationViewController alloc] initWithConversationType:model.conversationType targetId:model.targetId];
    conversationVC.conversationType = model.conversationType;
    conversationVC.targetId = model.targetId;
    conversationVC.titleStr = model.conversationTitle;
    if (model.conversationModelType == RC_CONVERSATION_MODEL_TYPE_NORMAL) {
        conversationVC.unReadMessage = model.unreadMessageCount;
        conversationVC.enableNewComingMessageIcon = YES; //开启消息提醒
        conversationVC.enableUnreadMessageIcon = YES;
    }
    [self.navigationController pushViewController:conversationVC animated:YES];
}

- (void)didTapCellPortrait:(RCConversationModel *)model {
    XMUserDetailViewController *vc = [[XMUserDetailViewController alloc] init];
    vc.userId = model.targetId;
    [self.navigationController pushViewController:vc animated:YES];
}

- (void)notifyUpdateUnreadMessageCount {
    dispatch_async(dispatch_get_main_queue(), ^{
//        [[AppDelegate sharedAppDelegate] updateUnreadCount];
        RCConnectionStatus status = [[RCCoreClient sharedCoreClient] getConnectionStatus];
        if (status != ConnectionStatus_SignOut) {
            [[RCCoreClient sharedCoreClient] getUnreadCount:@[
                @(ConversationType_PRIVATE),
                @(ConversationType_SYSTEM)
            ] completion:^(int count) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.navRightBtn.selected = count > 0;
                    [UIApplication sharedApplication].applicationIconBadgeNumber = count;
                    XMTabBarViewController *tabBar = (XMTabBarViewController *)[UIViewController currentViewController].tabBarController;
                    [tabBar.tabBarView setBadgeNum:count];
                });
            }];
        }
    });
}
- (NSMutableArray<RCConversationModel *> *)willReloadTableData:(NSMutableArray<RCConversationModel *> *)dataSource {
    NSMutableArray *tempArray = [NSMutableArray arrayWithArray:dataSource];
    [dataSource enumerateObjectsUsingBlock:^(RCConversationModel *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
        if (obj.conversationType == ConversationType_SYSTEM) {
            if ([obj.targetId isEqualToString:@"2"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.conversationListHeaderView.checkModel = obj;
                    [tempArray removeObject:obj];
                });
            }
            
            if ([obj.targetId isEqualToString:@"1"]) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    self.conversationListHeaderView.systemModel = obj;
                    [tempArray removeObject:obj];
                });
            }
        }
    }];
    return tempArray;
}

#pragma mark - lazy
//- (UIButton *)searchBtn {
//    if (_searchBtn == nil) {
//        _searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
//        [_searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
//        [_searchBtn setImage:kGetImage(@"msg_search") forState:UIControlStateNormal];
//        _searchBtn.titleLabel.font = kUIFontBold(14);
//        [_searchBtn setTitleColor:k1F1F1F forState:UIControlStateNormal];
//        [_searchBtn setImagePosition:(XMImagePositionLeft) spacing:6];
//        [_searchBtn addTarget:self action:@selector(search) forControlEvents:UIControlEventTouchUpInside];
//        [_searchBtn setBackgroundColor:kHEXA(@"#000000", 0.08)];
//        kCornerRadius(_searchBtn, 18, 0, UIColor.clearColor);
//    }
//    return _searchBtn;
//}

- (XMMsgNoRealView *)norealView {
    if (!_norealView) {
        _norealView = [XMMsgNoRealView viewFromXib];
        _norealView.layer.backgroundColor = [UIColor colorWithRed:255/255.0 green:255/255.0 blue:255/255.0 alpha:1.0].CGColor;
        _norealView.layer.cornerRadius = 10;
        _norealView.layer.shadowColor = [UIColor colorWithRed:0/255.0 green:0/255.0 blue:0/255.0 alpha:0.0900].CGColor;
        _norealView.layer.shadowOffset = CGSizeMake(0, 1);
        _norealView.layer.shadowOpacity = 1;
        _norealView.layer.shadowRadius = 5;
    }
    return _norealView;
}


- (XMDisturbTypeView *)disturbTypeView {
    if (_disturbTypeView == nil) {
        _disturbTypeView = [XMDisturbTypeView viewFromXib];
        _disturbTypeView.backgroundColor = UIColor.whiteColor;
        _disturbTypeView.size = CGSizeMake(kScreenWidth - 20, 196);
    }
    return _disturbTypeView;
}

- (void)showDisturbTypeView {
    self.disturbTypeView.disturb = kUserModel.is_mute;
    [GKCover coverFrom:kWindow contentView:self.disturbTypeView style:(GKCoverStyleTranslucent) showStyle:(GKCoverShowStyleBottom) showAnimStyle:(GKCoverShowAnimStyleNone) hideAnimStyle:(GKCoverHideAnimStyleNone) notClick:NO];
}

@end
